import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ToastController, LoadingController } from 'ionic-angular';
import { StorageProvider } from '../storage/storage';
/*
  Generated class for the HttpProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpProvider {

	public APPLE_ID = "wuliu998101";
	public APPLE_KEY = "key998101key998101key998101key998101";

	public APP_HTTP_URL = 'http://116.10.195.210:12682';
	public APP_SERVE_URL = '/ibcms/apis';

    //Observable => subscribe
	constructor(
		public http: HttpClient,
		public toastCtrl: ToastController,
		public loadingCtrl: LoadingController,
		public storage: StorageProvider) {
		console.log('Hello HttpProvider Provider');
		this.APP_SERVE_URL = this.APP_HTTP_URL + this.APP_SERVE_URL;
	}

	/**
	 * request请求
	 */
	public postJson(modal: any, action: any, data: any) {
		//post提交
		return new Promise((success) => {
			//检查token
			this.tokenToCheck().then(token => {
				//正常获取请求
				this.postData(modal, action, data, token).then(res => {
					if(success)
						success(res)
				});
			}, error => {
				//获取token之后
				this.postToken().then(token => {
					//正常获取请求
					this.postData(modal, action, data, token).then(res => {
						if(success)
							success(res)
					});
				});
			});
		});
	}

	/**
	 * 最终请求
	 */
	private postData(modal: any, action: any, data: any, token: any) {
		//post提交
		let url = this.APP_SERVE_URL + '/' + modal + '/' + action;
		//拼接口令
		if(token != "") {
			if(url.indexOf('?') > 0) {
				url = url + '&token=' + token;
			} else {
				url = url + '?token=' + token;
			}
		}
		//开始请求
		return new Promise((success, fail) => {
			// let loading = this.loadingCtrl.create({
			// 	content: '正在请求...'
			// });
			// loading.present();
			//发起请求
			this.http.post(url, this.toBodyString(data), {
				headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'),
				responseType: 'json'
			}).subscribe(result => {
					//请求结果
					success(this.handleSuccess(result));
				},
				error => {
					// loading.dismiss();
					this.toastMessage('网络请求异常');
				},
				() => {
					//请求完毕
					// loading.dismiss();
				});
		});
	}
	/**
	 * 请求成功
	 */
	private handleSuccess(result) {
		//此处是与后台约定
		if(result['status'] == 1) {
			return {
				success: true,
				data: result['data']
			};
		} else {
			if(result['msg'] == "token错误"){
				this.storage.removeStorage('token');
			}
			//统一请求
			return {
				success: false,
				msg: result['msg']
			};
		}
	}
	/**
	 * 令牌获取
	 */
	private postToken() {
		//登录成功
		return new Promise((success) => {
			let params = {
				"APPLE_ID": this.APPLE_ID,
				"APPLE_KEY": this.APPLE_KEY
			};
			//更新token
			this.postData('token', 'gettoken.do', params,"").then(res => {
				if(res['data'] != undefined) {
					//登录成功
					let params = {
						token: res['data']['token'],
						expires: res['data']['expires']
					};
					this.storage.saveStorage('token', params);
					//保存token
					if(success)
						success(res['data']['token']);
				}
			});
		});
	}

	/**
	 * 令牌判断
	 */
	private tokenToCheck() {
		//异步方式
		return new Promise((success, fail) => {
			//登录成功
			this.storage.getStorage('token').then(res => {
				//存在性
				if(res == undefined || res['token'] == undefined) {
					if(fail)
						fail();
				} else {
					//过期性
					let timestamp = (new Date().getTime()) / 1000;
					if(res['expires'] < timestamp) {
						if(fail)
							fail();
					} else {
						//成功性
						if(success)
							success(res['token']);
					}
				}
			});
		});
	}

	/**
	 * 拼接字符串
	 */
	private toBodyString(obj) {
		let ret = [];
		for(let key in obj) {
			key = encodeURIComponent(key);
			let values = obj[key];
			if(values && values.constructor == Array) { //数组
				let queryValues = [];
				for(let i = 0, len = values.length, value; i < len; i++) {
					value = values[i];
					queryValues.push(this.toQueryPair(key, value));
				}
				ret = ret.concat(queryValues);
			} else { //字符串
				ret.push(this.toQueryPair(key, values));
			}
		}
		return ret.join('&');
	}

	/**
	 * 拼接字符串
	 */
	private toQueryPair(key, value) {
		if(typeof value == 'undefined') {
			return key;
		}
		return key + '=' + encodeURIComponent(value === null ? '' : String(value));
	}

	/**
	 * 消息显示
	 */
	private toastMessage(message: any) {
		//请求异常
		this.toastCtrl.create({
			message: '网络请求异常',
			duration: 2000,
			position: 'top'
		}).present();
	}

}